class CreateUsers < ActiveRecord::Migration
    def self.up
        create_table "users", :force => true do |t|
            t.column "login", :string, :limit => 80, :default => "", :null => false
            t.column "salted_password", :string, :limit => 40, :default => "", :null => false
            t.column "email", :string, :limit => 60, :default => "", :null => false
            t.column "firstname", :string, :limit => 40
            t.column "lastname", :string, :limit => 40
            t.column "salt", :string, :limit => 40, :default => "", :null => false
            t.column "role", :string, :limit => 40
            t.column "security_token", :string, :limit => 40
            t.column "token_expiry", :datetime
            t.column "created_at", :datetime
            t.column "updated_at", :datetime
            t.column "logged_in_at", :datetime
            t.column "deleted", :integer, :default => 0
            t.column "delete_after", :datetime            
            # add column to keep user logged in
            t.column "remember_token_expires_at", :datetime
            t.column "remember_token", :string, :limit => 40
            # add fields for user verification        
            t.column "activation_code", :string, :limit => 40
            t.column "activated_at", :datetime
            t.column "password_reset_code", :string, :limit => 40 
        end
        
        add_index :users, :login
        
        add_index :annorations, :user_id
        add_index :annorations, :page_id
    
        execute "ALTER TABLE annorations ADD CONSTRAINT annorations_user_id_fkey FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE ON UPDATE CASCADE"
        execute "ALTER TABLE annorations ADD CONSTRAINT annorations_page_id_fkey FOREIGN KEY (page_id) REFERENCES pages (id) ON DELETE CASCADE ON UPDATE CASCADE"
    
        add_index :pages, :first_annoration_id
    
        execute "ALTER TABLE pages ADD CONSTRAINT pages_first_annoration_id_fkey FOREIGN KEY (first_annoration_id) REFERENCES annorations (id) ON DELETE CASCADE ON UPDATE CASCADE"
    end
    
    def self.down
        execute "ALTER TABLE annorations DROP CONSTRAINT annorations_user_id_fkey"
        execute "ALTER TABLE annorations DROP CONSTRAINT annorations_page_id_fkey"
        
        remove_index :annorations, :user_id
        remove_index :annorations, :page_id
    
        execute "ALTER TABLE pages DROP CONSTRAINT pages_first_annoration_id_fkey"
    
        remove_index :pages, :first_annoration_id
        
        drop_table :users
    end
end

        
